<template>
    <div style="padding-left: 30px;display: flex;flex-direction: column;gap: 20px;">
        <el-space spacer=" ">
            <el-button link>主图</el-button>
            <el-button type="primary" :disabled="!selectedItems.length" @click="handleMatting"> 抠图</el-button>
            <el-popover :visible="visible" placement="top" :width="330">
                <el-form :model="productImageFrom" label-width="auto" :rules="publicRules" ref="productImageFromRef">
                    <el-form-item label="上" prop="top" required>
                        <el-input-number v-model.trim="productImageFrom.top" placeholder="请输入" :min="0"
                            style="width: 250px;" />
                    </el-form-item>
                    <el-form-item label="下" prop="bottom" required>
                        <el-input-number v-model.trim="productImageFrom.bottom" placeholder="请输入" :min="0"
                            style="width: 250px;" />
                    </el-form-item>
                    <el-form-item label="左" prop="left" required>
                        <el-input-number v-model.trim="productImageFrom.left" placeholder="请输入" :min="0"
                            style="width: 250px;" />
                    </el-form-item>
                    <el-form-item label="右" prop="right" required>
                        <el-input-number v-model.trim="productImageFrom.right" placeholder="请输入" :min="0"
                            style="width: 250px;" />
                    </el-form-item>
                    <el-form-item label="羽化" prop="feathering">
                        <el-input-number v-model.trim="productImageFrom.feathering" placeholder="请输入" :min="0"
                            style="width: 250px;" />
                    </el-form-item>
                    <el-form-item label=" ">
                        <el-space spacer=" ">
                            <el-button type="primary" style="margin: 0 30px;" @click="handleSure">确定</el-button>
                            <el-button @click="handleCancel">取消</el-button>
                        </el-space>
                    </el-form-item>
                </el-form>
                <template #reference>
                    <el-button type="primary" :disabled="!selectedItems.length" @click="visible = true">扩图</el-button>
                </template>
            </el-popover>
            <el-button type="danger" :disabled="!selectedItems.length" @click="handleDelete">删除</el-button>
        </el-space>
        <el-space spacer=" " wrap>
            <el-space spacer=" " wrap style="width: 60px;height: 300px;">
                <el-text>原图</el-text>
                <el-text>效果图</el-text>
            </el-space>
            <div class="image_box" @scroll="handleScroll" ref="scrollPaneRef">
                <div v-for="(item, index) in imageList" :key="item.id" style="gap: 10px;">
                    <div class="image_relative" @click="toggleSelection(item)"
                        :class="{ 'selected-item': findImageId(item.id) }">
                        <div class="image_absolute">{{ item.newImageType }} - {{ item.id }}</div>
                        <el-icon class="icon_absolute" color="#409EFF" v-if="findImageId(item.id)"><Select /></el-icon>
                        <el-image style="width: 146px; height: 146px;border-radius: 5px;" :src="item.newMainImage"
                            fit="scale-down" />
                    </div>
                    <div @click="choseIndex(index)"
                        style="display: flex;align-items: center;flex-direction: column;height: 200px;">
                        <image-upload @baseUrl="handleBaseUrl" :isShowTip="false" v-model="item.trimmedPreSignedUrl"
                            :limit="1" v-if="item.processingStatus != '处理中'" />
                        <image-preview :src="item.trimmedPreSignedUrl" :width="146" :height="140"
                            style="margin: 10px 0;" v-else />
                        <el-button link type="primary" v-if="item.processingStatus == '处理成功'"
                            @click="handleSureImage(item)">确认</el-button>
                    </div>
                </div>
            </div>
        </el-space>
    </div>
</template>
<script setup>
import { ref, defineProps, defineEmits, watch, reactive, onMounted } from "vue";
const { proxy } = getCurrentInstance();
const { sys_image_type } = proxy.useDict("sys_image_type");
const imageList = ref();//照片列表
const imageIndex = ref(0); //上传照片获取下标
const visible = ref(false)
const selectedItems = ref([])//勾选数据的id
const handleTimes = ref(0)//循环调用接口时候需要用到

// 控制下拉菜单的显示状态
const productImageFrom = ref({
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
    feathering: 24
})

const props = defineProps({
    Item: {
        type: Object,
        default: {},
    },
    clearIndex: {
        type: Number,
        default: 0,
    },
    productImageType: {
        type: Number,//0是个人产品、1是公共产品、2是站点管理产品的
        default: null,
    }

});
watch(
    () => props.clearIndex,
    () => {
        if (!props.clearIndex) return;
        selectedItems.value = []
    }
);
// 查询参数
const queryParams = ref({
    pageNum: 1,
    pageSize: 20,
    param: {
        productId: null, //产品ID
    },
});
const total = ref(0)
let timer = null;
onMounted(() => {
    getList();
});

const getList = () => {
    if (props.productImageType === 2) {//2是站点管理产品的
        product.general
            .websiteproductGetproductimagelist({
                data: {
                    ...queryParams.value,
                    param: {
                        websiteProductId: props.Item.id,
                    }
                },
            })
            .then((res) => {
                total.value = res.total;
                if (res.data?.length) {
                    res.data = res.data.map((item) => {
                        return {
                            ...item,
                            newMainImage: item.originPreSignedUrl ? item.originPreSignedUrl : item.imageUrl,
                            viewLength: viewLength(item.originPreSignedUrl ? item.originPreSignedUrl : item.imageUrl),
                            newImageType: sys_image_type.value.find(
                                (e) => e.value === item.imageType
                            )?.label,
                        };
                    })
                }
                imageList.value = res.data
                // console.log(imageList.value, '[[[[[]]]]]');
            })
    } else if (props.productImageType === 1) {//1是公共产品
        product.general
            .publicproductGetproductimagelist({
                data: {
                    ...queryParams.value,
                    param: {
                        publicProductId: props.Item.id,
                    }
                },
            })
            .then((res) => {
                total.value = res.total;
                if (res.data?.length) {
                    res.data = res.data.map((item) => {
                        return {
                            ...item,
                            newMainImage: item.originPreSignedUrl ? item.originPreSignedUrl : item.imageUrl,
                            viewLength: viewLength(item.originPreSignedUrl ? item.originPreSignedUrl : item.imageUrl),
                            newImageType: sys_image_type.value.find(
                                (e) => e.value === item.imageType
                            )?.label,
                        };
                    })
                }
                imageList.value = res.data
                // console.log(imageList.value, '[[[[[]]]]]');
            })
    } else {//0是个人产品
        product.general
            .productGetcategoryimagelist({
                data: {
                    ...queryParams.value,
                    param: {
                        productId: props.Item.id,
                    }
                },
            })
            .then((res) => {
                total.value = res.total;
                if (res.data?.length) {
                    res.data = res.data.map((item) => {
                        return {
                            ...item,
                            newMainImage: item.originPreSignedUrl ? item.originPreSignedUrl : item.imageUrl,
                            viewLength: viewLength(item.originPreSignedUrl ? item.originPreSignedUrl : item.imageUrl),
                            newImageType: sys_image_type.value.find(
                                (e) => e.value === item.imageType
                            )?.label,
                        };
                    })
                }
                imageList.value = res.data
                // console.log(imageList.value, '[[[[[]]]]]');
            })

    }

}
const handleSure = () => {//确定按钮
    proxy.$refs["productImageFromRef"].validate((valid) => {
        if (!valid) return
        let newImageList = []
        // 宽：原来的宽度+left+right，高：原来的高度+bottom+top
        selectedItems.value.forEach(code => {
            console.log(code.viewLength, Number(productImageFrom.value.left));
            newImageList.push({
                id: code.id,
                width: code.viewLength.width + productImageFrom.value.left + productImageFrom.value.right,
                height: code.viewLength.height + productImageFrom.value.top + productImageFrom.value.bottom
            })
        })
        const hasLargeSizeBig = newImageList.some(item => item.width > 1024 || item.height > 1024);
        if (hasLargeSizeBig) return proxy.$modal.msgWarning("图片尺寸超过1024*1024，暂不支持进行图片修改操作");
        const hasLargeSize = newImageList.some(item => item.width > 800 || item.height > 800);
        handleTimes.value = 0

        if (hasLargeSize) {
            proxy.$modal.confirm('当前图片尺寸超过800X800，后台需要更多时间进行处理，请确定是否继续进行操作').then(() => {
                newImageList.forEach(code => {
                    enlargeImage(code.id, newImageList.length)
                })
            })
        } else {
            newImageList.forEach(code => {
                enlargeImage(code.id, newImageList.length)
            })
        }
    })
}
const enlargeImage = (id, length) => {
    if (props.productImageType === 2) {//2是站点管理产品的
        handleTimes.value += 1
        product.general.websiteproductExpandedimage({
            data: {
                ...productImageFrom.value,
                id: id,
            }
        }).then(res => {
            if (res.code === 200 && handleTimes.value === length) {
                selectedItems.value = []
                getList();
                proxy.$modal.msgSuccess(res.message)
            }
        })
    } else if (props.productImageType === 1) {//公共产品
        handleTimes.value += 1
        product.general.publicproductExpandedimage({
            data: {
                ...productImageFrom.value,
                id: id,
            }
        }).then(res => {
            if (res.code === 200 && handleTimes.value === length) {
                selectedItems.value = []
                getList();
                proxy.$modal.msgSuccess(res.message)
            }
        })
    } else {
        handleTimes.value += 1
        product.general.productExpandedimage({
            data: {
                ...productImageFrom.value,
                id: id,
            }
        }).then(res => {
            if (res.code === 200 && handleTimes.value === length) {
                selectedItems.value = []
                getList();
                proxy.$modal.msgSuccess(res.message)
            }
        })
    }
}

const handleMatting = () => {//抠图
    handleTimes.value = 0
    proxy.$modal.confirm("是否确认处理勾选的数据？").then(() => {
        selectedItems.value.forEach(code => {
            mattingImage(code)
        })
    })
}
// 滑动加载照片数据
const handleScroll = (e) => {
    const { scrollWidth, scrollLeft, clientWidth } = proxy.$refs["scrollPaneRef"]
    const distanceToEnd = scrollWidth - scrollLeft - clientWidth;
    // console.log('距离', distanceToEnd);
    // 条件 1：数据已加载完毕，不再请求
    if (!distanceToEnd && total.value === imageList.value.length) {
        proxy.$modal.msgWarning("没有更多图片，请勿重复操作");
    } else {
        // 条件 2：滚动到接近底部，并使用防抖
        if (total.value != imageList.value.length && distanceToEnd <= 400 && distanceToEnd >= 0) {
            if (timer) return; // 防止短时间内连续触发

            timer = setTimeout(() => {
                queryParams.value.pageSize += 10;
                getList();
                timer = null; // 释放定时器，允许下次触发
            }, 1000);
        }

    }

}
// 抠图
const mattingImage = (row) => {
    if (props.productImageType === 2) {//2是站点管理产品的
        // product.general.websiteproductTrimimag({

        handleTimes.value += 1
        product.general
            .websiteproductTrimimag({
                data: {
                    id: row.id,
                },
            })
            .then((res) => {
                if (res.code !== 200) return;
                if (handleTimes.value === selectedItems.value.length) {
                    getList();
                    selectedItems.value = [];
                    proxy.$modal.msgSuccess(res.message);
                }
            });
    } else if (props.productImageType === 1) {
        handleTimes.value += 1
        product.general
            .publicproductTrimimage({
                data: {
                    id: row.id,
                },
            })
            .then((res) => {
                if (res.code !== 200) return;
                if (handleTimes.value === selectedItems.value.length) {
                    getList();
                    selectedItems.value = [];
                    proxy.$modal.msgSuccess(res.message);
                }
            });
    } else {
        handleTimes.value += 1
        product.general
            .productTrimimage({
                data: {
                    id: row.id,
                },
            })
            .then((res) => {
                if (res.code !== 200) return;
                if (handleTimes.value === selectedItems.value.length) {
                    getList();
                    selectedItems.value = [];
                    proxy.$modal.msgSuccess(res.message);
                }
            });
    }
};
// 确认修改图片
const handleSureImage = (row) => {
    proxy.$modal
        .confirm("是否确认并保存？")
        .then(() => {
            product.product.productConfirmtrimimage(
                { data: { id: row.id } }
            ).then(res => {
                if (res.code === 200) {
                    getList()
                    selectedItems.value = [];
                    proxy.$modal.msgSuccess("操作成功");
                }
            })
        })
}

const findImageId = (id) => {
    return selectedItems.value.find(item => item?.id === id)
}
const toggleSelection = (code) => {
    if (findImageId(code.id)) {  // 如果已选中，移除
        selectedItems.value = selectedItems.value.filter(item => item.id !== code.id);
    } else {
        selectedItems.value.push(code);// 未选中，添加
    }
};
const handleBaseUrl = (val) => {
    product.general.productUpdateimage({
        data: {
            id: imageList.value[imageIndex.value].id,
            url: val.url
        }
    }).then((res) => {
        if (res.code === 200) {
            imageList.value[imageIndex.value].trimmedPreSignedUrl = val.preSignedUrl;
            proxy.$modal.msgSuccess(res.message);
        }
    });
};
const handleDelete = () => {
    let newIds = []
    if (!selectedItems.value.length) return proxy.$modal.msgWarning("请勾选数据");
    const hasMainOrKeu = selectedItems.value.some(item => item.imageType === "main" || item.imageType === "keu");
    if (hasMainOrKeu)
        return proxy.$modal.msgWarning("不支持删除主图或者SKU图");
    proxy.$modal.confirm("是否确认删除勾选的数据？").then(() => {
        newIds = selectedItems.value.map(item => item.id)
        publicDeleteImage(newIds)
    })
};

const publicDeleteImage = (newIds) => {
    if (props.productImageType === 2) {//2是站点管理产品的
        product.general
            .websiteproductBatchdeleteimage({
                data: { ids: newIds, },
            })
            .then((res) => {
                if (res.code === 200) {
                    selectedItems.value = [];
                    getList();
                    proxy.$modal.msgSuccess("操作成功");
                }
            });
    } else if (props.productImageType === 1) {//公共
        product.general
            .publicproductBatchdeleteimage({
                data: { ids: newIds, },
            })
            .then((res) => {
                if (res.code === 200) {
                    selectedItems.value = [];
                    getList();
                    proxy.$modal.msgSuccess("操作成功");
                }
            });
    } else {
        product.general
            .productBatchdeleteimage({
                data: { ids: newIds, },
            })
            .then((res) => {
                if (res.code === 200) {
                    selectedItems.value = [];
                    getList();
                    proxy.$modal.msgSuccess("操作成功");
                }
            });
    }
}
const choseIndex = (index) => {
    imageIndex.value = index;// 照片的host赋值
};

const handleCancel = () => {
    processingClose()
}
const viewLength = (url) => {
    if (!url) return 0
    let img = new Image();
    img.src = url;
    img.onload = function () {
        return img.width;
    }
    return {
        width: img.width,
        height: img.height,
    }
}
const processingClose = () => {
    proxy.resetForm("productImageFromRef");
    visible.value = false
}
const publicRules = reactive({
    left: [
        { required: true, message: '请输入', trigger: 'blur' },
        {
            pattern: /^[1-9]\d*$|^0$/,
            message: "只能输入0以上的整数",
            trigger: "blur",
        },
    ],
    top: [
        { required: true, message: '请输入', trigger: 'blur' }, {
            pattern: /^[1-9]\d*$|^0$/,
            message: "只能输入0以上的整数",
            trigger: "blur",
        },
    ],
    right: [
        { required: true, message: '请输入', trigger: 'blur' },
        {
            pattern: /^[1-9]\d*$|^0$/,
            message: "只能输入0以上的整数",
            trigger: "blur",
        },
    ],
    bottom: [
        { required: true, message: '请输入', trigger: 'blur' },
        {
            pattern: /^[1-9]\d*$|^0$/,
            message: "只能输入0以上的整数",
            trigger: "blur",
        },
    ],
    feathering: [
        {
            pattern: /^[1-9]\d*$|^0$/,
            message: "只能输入0以上的整数",
            trigger: "blur",
        }]
})

</script>
<style lang="scss" scoped>
.image_box {
    width: calc(100vw - 300px);
    display: flex;
    gap: 30px;
    overflow-x: auto;
    position: relative;
    margin-bottom: 40px;

    >div {
        display: flex;
        flex-direction: column;
    }
}

.image_absolute {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    background-color: #333;
    color: #fff;
    font-size: 10px;
    padding: 2px;
}

.icon_absolute {
    position: absolute;
    top: 3px;
    right: 0px;
    z-index: 1;
}

.image_relative {
    position: relative;
    // background-color: aqua;
}

.selected-item {
    border: 2px solid #03b3b2;
    /* 选中时边框变红 */
    box-shadow: 0 0 10px rgba(78.6, 201.8, 201.1);
}
</style>